#include "tupdatedialog.h"
#include "ui_tupdatedialog.h"

TupdateDialog::TupdateDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TupdateDialog)
{
    ui->setupUi(this);
    this->resize(300,300);
    ui->btnUpgrade->setEnabled(false);
    ui->progressBar->hide();
}

TupdateDialog::~TupdateDialog()
{
    delete ui;
}

void TupdateDialog::checkForUpdate()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onUpdateCheckFinished(QNetworkReply*)));
    QNetworkRequest request(QUrl("https://gitee.com/wangyoufeng/at-command-tools/releases/latest"));
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
    request.setRawHeader("Accept","*/*");
    manager->get(request);
}

void TupdateDialog::onUpdateCheckFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray response_data = reply->readAll();
        //qDebug()<<response_data;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(response_data);
        QJsonObject jsonObj = jsonDoc.object();
        latestVersion = jsonObj["release"].toObject()["tag"].toObject()["name"].toString();
        QString currentVersion = QString(TOOLSVERSION); // 获取当前版本号，可以从配置文件或代码中获得
        qDebug()<<latestVersion<<currentVersion;

        if (latestVersion > currentVersion) {
            downloadUrl = jsonObj.value("release").toObject().value("release").toObject().value("attach_files")[0].toObject().value("cli_download_url").toString();
            QString description = jsonObj.value("release").toObject().value("release").toObject().value("description").toString();
            // 这里可以启动下载
            ui->plainTextEditUpdateInfo->setPlainText("发现新版本:"+latestVersion+"\n是否升级?");
            // ui->textBrowserUpdateInfo->setHtml(description);
            ui->textBrowserUpdateInfo->setMarkdown(description);
            ui->btnUpgrade->setEnabled(true);
        }
        else
        {
            ui->plainTextEditUpdateInfo->setPlainText("未发现新版本");
        }
    }
    else
    {
        ui->plainTextEditUpdateInfo->setPlainText("未成功查询新版本");
    }
    ui->plainTextEditUpdateInfo->moveCursor(QTextCursor::End);
    reply->deleteLater();
}
void TupdateDialog::downloadUpdate(const QString &url)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onUpdateDownloadFinished(QNetworkReply*)));
    //QNetworkRequest request(QUrl("https://gitee.com/wangyoufeng/at-command-tools/releases/download/V1.1/atCommandTools.7z"));
    QUrl url1(url);
    QNetworkRequest request(url1);
    QNetworkReply *reply = manager->get(request);

    QObject::connect(reply,&QNetworkReply::downloadProgress,[&](qint64 bytesReceived, qint64 bytesTotal){
        //ui->plainTextEditUpdateInfo->insertPlainText(QString("\n总共:%1Bytes,已下载:%2Bytes,进度:%3").arg(bytesTotal).arg(bytesReceived).arg(bytesReceived/bytesTotal));
        //qDebug()<<"下载中"<<bytesReceived<<bytesTotal;
        ui->progressBar->setValue(bytesReceived*100/bytesTotal);
    });
    // QObject::connect(reply,&QNetworkReply::finished,[&](){
    //     qDebug()<<"onUpdateDownloadFinished start";
    //     if (reply->error() == QNetworkReply::NoError) {
    //         QByteArray response_data = reply->readAll();
    //         QFile file("../update.zip");
    //         if (file.open(QIODevice::WriteOnly)) {
    //             file.write(response_data);
    //             file.close();
    //             ui->plainTextEditUpdateInfo->insertPlainText("\n下载成功");
    //             applyUpdate();
    //         }
    //         else
    //         {
    //             ui->plainTextEditUpdateInfo->insertPlainText("\n下载保存失败");
    //         }
    //     }
    //     else
    //     {
    //         ui->plainTextEditUpdateInfo->insertPlainText("\n下载失败");
    //     }
    //     ui->plainTextEditUpdateInfo->moveCursor(QTextCursor::End);
    //     reply->deleteLater();
    // });
}

void TupdateDialog::onUpdateDownloadFinished(QNetworkReply *reply)
{
    qDebug()<<"onUpdateDownloadFinished start";
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray response_data = reply->readAll();
        QFile file("../update.zip");
        if (file.open(QIODevice::WriteOnly)) {
            file.write(response_data);
            file.close();
            ui->plainTextEditUpdateInfo->insertPlainText("\n下载成功");
            applyUpdate();
        }
        else
        {
            ui->plainTextEditUpdateInfo->insertPlainText("\n下载保存失败");
        }
    }
    else
    {
        ui->plainTextEditUpdateInfo->insertPlainText("\n下载失败");
    }
    ui->plainTextEditUpdateInfo->moveCursor(QTextCursor::End);
    reply->deleteLater();
}
void TupdateDialog::applyUpdate()
{
    QString zipFilePath = "../update.zip";
    QString extractTo = QCoreApplication::applicationDirPath()+"/../update";
    ui->plainTextEditUpdateInfo->insertPlainText("\n开始解压");
    zip_decompress(zipFilePath, extractTo);
    ui->plainTextEditUpdateInfo->insertPlainText("\n解压完成\n正在重启");
    QString launcher = QDir::cleanPath(extractTo+QDir::separator()+".."+QDir::separator()+"update.exe");
    qDebug()<<launcher;
    QProcess::startDetached(launcher,QStringList());
    qApp->quit();
    //exit(0);
}

/**
 * @brief 压缩文件
 * @param fileNames 需要压缩的文件绝对路径
 * @param path 压缩后的文件的绝对路径
 */
void TupdateDialog::zip_compress(const QStringList &fileNames, const QString &path)
{
  QZipWriter *zipWriter = new QZipWriter(path);
  foreach (const QString &fileName, fileNames) {
    if (fileName.isEmpty()) continue;
    QFileInfo fileInfo(fileName);
    if (!fileInfo.exists()) continue;
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) continue;
    zipWriter->addFile(fileInfo.fileName(), file.readAll());
    file.close();
  }
  zipWriter->close();
  if (zipWriter) {
    delete zipWriter;
    zipWriter = nullptr;
  }
}
/**
 * @brief 解压缩文件
 * @param fileName 需要解压缩的文件
 * @param path 解压后文件存放的目录
 */
void TupdateDialog::zip_decompress(const QString &fileName, const QString &path)
{
  if (fileName.isEmpty()) {
    return;
  }
  QFileInfo fileInfo(fileName);
  if (!fileInfo.exists()) {
    return;
  }
  QString dirName = QDir::cleanPath(path);
  QDir dir(dirName);
  if (!dir.exists())
  {
    if(dir.mkdir(dirName))
    {
        ui->plainTextEditUpdateInfo->insertPlainText("\n创建:"+dirName+"成功");
    }
    else
    {
        ui->plainTextEditUpdateInfo->insertPlainText("\n创建:"+dirName+"失败");
        return;
    }
  }
  else
  {
    if(dir.removeRecursively())
    {
        ui->plainTextEditUpdateInfo->insertPlainText("\n清空:"+dirName+"成功");
    }
    else
    {
        ui->plainTextEditUpdateInfo->insertPlainText("\n清空:"+dirName+"失败");
        return;
    }
  }

  QZipReader *reader = new QZipReader(fileName);
  foreach (const QZipReader::FileInfo &info, reader->fileInfoList()) {
    if (!info.isDir) {
      QString filePath = QDir::cleanPath(path + QDir::separator() + info.filePath);
      QFile file(filePath);
      qDebug()<<"filePath"<<filePath;
      if (!file.open(QIODevice::WriteOnly)) {
        ui->plainTextEditUpdateInfo->insertPlainText("\n复制:"+filePath+"失败");
        ui->plainTextEditUpdateInfo->moveCursor(QTextCursor::End);
        continue;
      }
      file.write(reader->fileData(info.filePath));
      file.close();
      ui->plainTextEditUpdateInfo->insertPlainText("\n复制:"+filePath+"成功");
      ui->plainTextEditUpdateInfo->moveCursor(QTextCursor::End);
    } else {
      QString dirName = QDir::cleanPath(path + QDir::separator() + info.filePath);
      QDir dir(dirName);
      qDebug()<<"dirName"<<dirName;
      if (!dir.exists())
      {
          if(dir.mkdir(dirName))
          {
              ui->plainTextEditUpdateInfo->insertPlainText("\n创建:"+dirName+"成功");
          }
          else
          {
              ui->plainTextEditUpdateInfo->insertPlainText("\n创建:"+dirName+"失败");
          }
          ui->plainTextEditUpdateInfo->moveCursor(QTextCursor::End);
      }
    }
  }
  reader->close();
  // if (reader) {
  //   delete reader;
  //   reader = nullptr;
  // }
  dir.remove(fileName);
}


void TupdateDialog::on_btnUpgrade_clicked()
{
    ui->progressBar->show();
    ui->btnUpgrade->hide();
    if(!downloadUrl.isEmpty())
    {
        downloadUpdate(downloadUrl);
    }
    else
    {
        ui->plainTextEditUpdateInfo->setPlainText("未找到下载链接");
        ui->plainTextEditUpdateInfo->moveCursor(QTextCursor::End);
    }
}

